package com.medical.app.service.impl;

import com.medical.app.entity.Medication;
import com.medical.app.repository.MedicationRepository;
import com.medical.app.service.MedicationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class MedicationServiceImpl implements MedicationService {

    @Autowired
    private MedicationRepository medicationRepository;

    @Override
    public List<Medication> getUserMedications(Long userId) {
        return medicationRepository.findByUserIdOrderByStartDateDesc(userId);
    }

    @Override
    public Medication saveMedication(Medication medication) {
        return medicationRepository.save(medication);
    }

    @Override
    public Medication updateMedication(Long id, Medication medication) {
        Optional<Medication> existingMedication = medicationRepository.findById(id);
        if (existingMedication.isPresent()) {
            Medication medicationToUpdate = existingMedication.get();
            // 更新所有字段
            medicationToUpdate.setName(medication.getName());
            medicationToUpdate.setDosage(medication.getDosage());
            medicationToUpdate.setFrequency(medication.getFrequency());
            medicationToUpdate.setStartDate(medication.getStartDate());
            medicationToUpdate.setEndDate(medication.getEndDate());
            medicationToUpdate.setNotes(medication.getNotes());
            medicationToUpdate.setReminder(medication.getReminder());
            medicationToUpdate.setImageUrls(medication.getImageUrls());
            return medicationRepository.save(medicationToUpdate);
        } else {
            throw new RuntimeException("药品记录不存在");
        }
    }

    @Override
    public void deleteMedication(Long id) {
        medicationRepository.deleteById(id);
    }

    @Override
    public Optional<Medication> findById(Long id) {
        return medicationRepository.findById(id);
    }

    @Override
    public long getMedicationCount(Long userId) {
        return medicationRepository.countByUserId(userId);
    }
}